package com.luoying.itew.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonSharePoint;
import com.amap.api.services.share.ShareSearch;
import com.luoying.itew.R;
import com.luoying.itew.adapter.WaitListAdapter;
import com.luoying.itew.adapter.WaitListAdapter.WaitListOnItemClickListener;
import com.luoying.itew.bean.MonitorBean;
import com.luoying.itew.common.Constant;
import com.luoying.itew.manage.UserManage;
import com.luoying.itew.util.StateContext;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by lufan on 2018/6/4
 * Class describe 待办事项列表 显示报警点数据
 */
public class WaitActivity extends BaseActivity implements WaitListOnItemClickListener , ShareSearch.OnShareSearchListener  {
    Toolbar waitToolbar;
    @BindView(R.id.wait_rv)
    RecyclerView waitRv;
    //适配器
    WaitListAdapter adapter;

    /**
     * 高德地图生成短传链接
     */
    private ShareSearch mShareSearch;

    /**
     * 微信开放平台
     */
    private IWXAPI iwxapi;
    /**
     * 分享监测点临时存放对象
     */
    private MonitorBean tempBean;
    private int districtId;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        districtId = this.getIntent().getIntExtra("districtId",0);
        List<MonitorBean> data = new ArrayList<>();
        for (MonitorBean monitorPoint : UserManage.getInstance().getDistricById(districtId).getMonitorPoints()) {
            if(new StateContext(monitorPoint.getMonitorPointStatus(),
                    monitorPoint.getWarnCoefficient()).stateLeve()!= Constant.WARN_LEVEL_GREEN){
                data.add(monitorPoint);
            }
        }
        adapter = new WaitListAdapter(data);
        waitRv.setAdapter(adapter);
        adapter.setListener(this);
        mShareSearch = new ShareSearch(this.getApplicationContext());
        mShareSearch.setOnShareSearchListener(this);
        regToWx();

    }

    @Override
    protected void InitActionBar() {
        super.InitActionBar();
        waitToolbar = (Toolbar) findViewById(R.id.wait_toolbar);
        setSupportActionBar(waitToolbar);
        ActionBar actionBar =  getSupportActionBar();
        if(actionBar != null ) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setDisplayShowTitleEnabled(false);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return true;
    }

    @Override
    public int getLayoutResId() {
        return R.layout.activity_wait;
    }


    @Override
    public void onClick(MonitorBean bean) {
        Intent intent = new Intent(this, InformationActivity.class);
        intent.putExtra("cuurMonitorId", bean.getMonitorPointId());
        startActivity(intent);
    }

    @Override
    public void onShareWx(MonitorBean bean) {
        //高德地图 位置分享生成位置链接 异步
        LatLonSharePoint point = new LatLonSharePoint(bean.getBdLat(),
                bean.getBdLng(), "安泰监测点："+bean.getMonitorPointName());
        //临时存放对想
        tempBean = bean;
        mShareSearch.searchLocationShareUrlAsyn(point);
    }

    /**
     * 注册微信
     */
    public void regToWx(){
        iwxapi = WXAPIFactory.createWXAPI(this, Constant.WEIXIN_OPEN_ID, true);
        iwxapi.registerApp(Constant.WEIXIN_OPEN_ID);
    }

    /**
     * 分享到微信
     * @param url 链接地址
     */
    public void shareLocationToWx(String url){
        //初始化一个WXWebpageObject，填写url
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = url;

        //用 WXWebpageObject 对象初始化一个 WXMediaMessage 对象
        WXMediaMessage msg = new WXMediaMessage(webpage);
        //标题
        msg.title = getString(R.string.share_wx_title);
        StateContext stateContext = new StateContext(tempBean.getMonitorPointStatus(),tempBean.getWarnCoefficient());
        //描述
        msg.description = String.format(getString(R.string.share_wx_description), tempBean.getMonitorArea().getDistrictName(),
                tempBean.getMonitorPointName(), stateContext.levelStr());
        Bitmap thumbBmp = BitmapFactory.decodeResource(getResources(), R.drawable.antai);
        msg.thumbData =bmpToByteArray(thumbBmp, true);

        //构造一个Req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = "webpage" + System.currentTimeMillis();
        req.message =msg;
        req.scene =SendMessageToWX.Req.WXSceneSession;

        //调用api接口，发送数据到微信
        iwxapi.sendReq(req);
    }

    public  byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bmp.recycle();
        }

        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    @Override
    public void onPoiShareUrlSearched(String s, int i) {

    }



    @Override
    public void onNaviShareUrlSearched(String s, int i) {

    }

    @Override
    public void onBusRouteShareUrlSearched(String s, int i) {

    }

    /**
     * 位置分享的异步处理
     * @param s
     * @param i
     */
    @Override
    public void onLocationShareUrlSearched(String s, int i) {
        if(i == AMapException.CODE_AMAP_SUCCESS||tempBean==null){
            //生成成功 分享微信
            shareLocationToWx(s);
        } else{
            Toast.makeText(this, "分享失败", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onWalkRouteShareUrlSearched(String s, int i) {

    }

    @Override
    public void onDrivingRouteShareUrlSearched(String s, int i) {

    }
}
